package com.huangkailong.designpattern.proxy.dynamicproxy;

import com.huangkailong.designpattern.proxy.common.DatasourceSupport;
import com.huangkailong.designpattern.proxy.common.Order;
import com.huangkailong.designpattern.proxy.common.OrderDao;
import com.huangkailong.designpattern.proxy.common.OrderService;
import com.huangkailong.designpattern.proxy.common.OrderServiceImpl;
import com.huangkailong.designpattern.proxy.common.OrderServiceTest;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 动态代理测试.
 *
 * @author huangkl
 * @since 1.0.0
 */
public class Client {
    private static final DateTimeFormatter YEAR_PATTERN = DateTimeFormatter.ofPattern("yyyy");

    /**
     * main 方式.
     */
    public static void main(String[] args) {

        OrderServiceImpl orderServiceImpl = new OrderServiceImpl(new OrderDao());
        DatasourceSupport datasourceSupport = new DatasourceSupport();

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        OrderService orderService =
            ProxyUtil.newProxyInstance(contextClassLoader, OrderService.class,
                new ProxyInterceptor() {
                    @Override
                    public Object getTarget() {
                        return orderServiceImpl;
                    }

                    @Override
                    public void before(Object proxy, Method method, Object[] args) {
                        if (args != null && args.length > 0) {
                            Object arg = args[0];
                            if (arg instanceof Order) {
                                Order order = (Order) arg;
                                LocalDateTime createdTime = order.getCreatedTime();
                                String year = createdTime.format(YEAR_PATTERN);
                                String datasourceName = "t_test_" + year;
                                System.out.printf("通过动态代理，动态的把数据库切换到了：%s\n", datasourceName);
                                datasourceSupport.setDatasourceName(datasourceName);
                            }
                        }
                    }
                });

        OrderServiceTest.testProxy(orderService);
    }
}
